import React, {Component} from 'react';
import {Modal, Segmented, Space, Table, Tag, Typography} from "antd";
import TheImage from "@/components/TheImage";
import "../style/style.less";
import {
    apiShopOrderDetail,
    apifindOrderOutLibraryList,
    apifindOrderOutLibraryDetail
} from "@/request/orderManagement";

const {Paragraph} = Typography;

class StockOutModal extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isModalOpen: false,
            columns: [
                {
                    title: "商品信息",
                    render: (text, record, index) => {
                        let status = ''
                        switch (record.salesStatus) {
                            case '1':
                                status = '(退款中)'
                                break;
                            case '2':
                                status = '(已退款)'
                                break;
                        }
                        return (
                            <div
                                style={{
                                    display: "flex",
                                    alignItems: "center",
                                    cursor: "pointer",
                                }}
                            >
                                <TheImage src={record.goodsImage} width={100} height={100}/>
                                <span
                                    style={{
                                        margin: "0 10px",
                                        maxWidth: '250px',
                                        wordWrap: 'break-word', /* 允许在单词内换行 */
                                        overflowWrap: 'break-word', /* 同上，现代浏览器推荐使用 */
                                        whiteSpace: 'normal', /* 允许自动换行 */
                                    }}
                                    onClick={() => {
                                        this.props.history.push(
                                            `/mall/list/detail/${record.productSkuJson[index].goodsId}`
                                        );
                                    }}
                                >
                                    {record.goodsName}{status}
                                </span>
                                <span>{record.sku}</span>
                                {/*{record.giftId !== "0" && <div className="gift">赠</div>}*/}
                            </div>
                        );
                    },
                },
                {
                    title: "商品物料名称(仓库用 APP不显示)",
                    dataIndex: "materialName",
                    key: "materialName",
                    render: (text) => text || "",
                },
                {
                    title: "物料ID",
                    dataIndex: "materialId",
                    key: "materialId",
                    render: (text) => text || "",
                },
                {
                    title: "商品单价",
                    dataIndex: "orderPrice",
                    key: "orderPrice",
                    render: (text, render) => {
                        return <>
                            <React.$price price={text || 0}/>
                            {

                                render.activityType === 'SECKILL_HOMEPAGE' && <div style={{color: 'red'}}>秒杀价</div>
                            }
                            {
                                render.activityType === 'TEAM_BUY' && <Tag color="red">拼团价</Tag>
                            }
                        </>
                    },
                },
                {
                    title: "商品数量",
                    dataIndex: "orderProductCount",
                    key: "orderProductCount",
                    render: (text) => text || 0,
                },
                {
                    title: "商品可用数量",
                    dataIndex: "goodsResidueCount",
                    key: "goodsResidueCount",
                    render: (text) => text || 0,
                },
                // {
                //     title: "备注",
                //     dataIndex: "skuDescription",
                //     key: "skuDescription",
                //     render: (text) => text || '',
                // },
                // {
                //     title: "总计",
                //     dataIndex: "orderPriceTotal",
                //     key: "orderPriceTotal",
                //     render: (text) => <React.$price price={text || 0}/>,
                // },
                // {
                //     title: "实付金额",
                //     dataIndex: "detailPayPrice",
                //     key: "detailPayPrice",
                //     render: (text) => <React.$price price={text || 0}/>,
                // }
            ],
            dataSource: [],
            goodsSumPrice: 0,
            goodsSum: 0,
            options: [],
            orderId: null,
            orderState: null,
            ckCode: null,
            ckInfo: {},
            footBtns: false,
            footBtnsType: null
        }
    }

    getData = async (id) => {
        await apifindOrderOutLibraryDetail({code: id}).then(res => {
            if (res.code === 0) {
                const productSkuJson = res.data.shopOrderGoodsDetailVos;
                const productData = productSkuJson.map((v) => {
                    let arr = JSON.parse(v.goodsSkuJson);
                    return {
                        materialId: v.materialId,
                        materialName: v.materialName,
                        goodsName: v.goodsName,
                        orderPrice: v.orderPrice,
                        orderProductCount: v.orderProductCount,
                        // orderPriceTotal: v.orderPriceTotal,
                        sku:
                            arr.hasOwnProperty("skuAttribute") &&
                            arr.skuAttribute.map((j) => {
                                return j.value;
                            }),
                        giftId: v.giftId,
                        activityType: v.activityType,
                        orderPriceTotal: v.orderPriceTotal, // 原价
                        detailDiscountsPrice: v.detailDiscountsPrice, // 优惠金额
                        detailPayPrice: v.detailPayPrice, //实付价
                        goodsImage: v.goodsImage,
                        productSkuJson,
                        skuId: arr.hasOwnProperty("skuAttribute") && arr.SKUId,
                        key: v.shopOrderDetailId,
                        salesStatus: v.salesStatus,
                        skuDescription: v.skuDescription,
                        goodsResidueCount: v.goodsResidueCount //商品可用数量
                    };
                });
                let footBtns = this.props.footer;
                let {footBtnsType, orderState} = this.state;
                // 按订单状态进行功能按钮的二级过滤
                // 发货send时
                if (footBtnsType === 'send' && res.data.state === '1') {
                    footBtns = footBtns.filter(item => (item.key !== 'send'))
                } else if (footBtnsType === 'courier') {
                    if (orderState === '9') {
                        footBtns = footBtns.filter(item => (item.key !== 'courier'))
                    } else if (res.data.state === '0') {
                        footBtns = []
                    }
                }
                // 委外仓的出库单，不显示发货、修改快递按钮
                if (res.data.isOutsourceShipments) {
                    footBtns = footBtns.filter(item => (item.key !== 'send' && item.key !== 'courier'))
                }
                this.setState({
                    dataSource: productData,
                    goodsSumPrice: res.data.goodsSumPrice,
                    goodsSum: res.data.goodsSum,
                    ckInfo: res.data,
                    footBtns
                })
            }
        })
    }
    open = async (orderId, type, orderState) => {
        this.setState({
            orderId,
            orderState,
            footBtnsType: type
        }, async () => {
            await this.getList()
        })
    }
    close = () => {
        this.setState({
            isModalOpen: false
        })
    }
    getList = async () => {
        await apifindOrderOutLibraryList({orderId: this.state.orderId}).then(res => {
            if (res.code === 0) {
                let options = res.data.map(item => {
                    return {
                        label: `${item.code}(${item.status ? '已完成' : '未完成'})`,
                        value: item.code,
                        // disabled: item.status
                    }
                })
                this.setState({
                    isModalOpen: true,
                    options,
                    ckCode: res.data[0].code
                })
                this.getData(res.data[0].code)
            }

        })
    }
    handleCancel = () => {
        this.setState({
            isModalOpen: false
        })
    }
    segmentedChange = (value) => {
        this.setState({
            ckCode: value
        })
        this.getData(value)
    }
    getCkCode = () => {
        return this.state.ckCode
    }
    getCkInfo = () => {
        return this.state.ckInfo
    }
    getCourier = () => {
        let {ckInfo} = this.state
        if (ckInfo.courierCode === 'HQM') {
            return 'delivery'
        } else {
            return 'courier'
        }
    }
    transCourier2Label = (code) => {
        let options = this.props.courierList, str = '-'
        for (let i = 0; i < options.length; i++) {
            if (options[i].value === code) {
                str = options[i].label
            }
        }
        return str
    }

    render() {
        let {
            isModalOpen,
            columns,
            dataSource,
            goodsSumPrice,
            goodsSum,
            options,
            ckCode,
            ckInfo,
            footBtns
        } = this.state;
        return (
            <Modal
                width={'80%'}
                title="出库单"
                visible={isModalOpen}
                destroyOnClose={true}
                maskClosable={false}
                onCancel={this.handleCancel}
                footer={footBtns}
            >
                <Segmented
                    options={options}
                    value={ckCode}
                    onChange={this.segmentedChange}
                />
                <Paragraph>
                    <blockquote>出库单信息</blockquote>
                </Paragraph>
                <Space size={40} style={{marginBottom: 15}}>
                    <span>发货仓库：{ckInfo.name}</span>
                    <span>快递公司：{this.transCourier2Label(ckInfo.courierCode)}</span>
                    {
                        ckInfo.courierCode === 'HQM' ? <span>快递员：{ckInfo.deliverymanName ?? '-'}</span> :
                            <span>物流单号：{ckInfo.courierNo ?? '-'}</span>
                    }
                </Space>
                <Table
                    className={'order-details'}
                    dataSource={dataSource}
                    columns={columns}
                    pagination={false}
                    bordered
                    scroll={{
                        x: '100%',
                        y: 500
                    }}
                    summary={(pageData) => {
                        return (
                            <Table.Summary fixed>
                                <Table.Summary.Row>
                                    <Table.Summary.Cell colSpan={9} index={0}>
                                        <div style={{textAlign: "center"}}>
                                            {`共${goodsSum}件商品，总计`}<React.$price price={goodsSumPrice || 0}/>元
                                        </div>
                                    </Table.Summary.Cell>
                                </Table.Summary.Row>
                            </Table.Summary>
                        );
                    }}
                />
            </Modal>
        );
    }
}

export default StockOutModal;
